'use client';

import useToast from '@/hooks/useToast';
import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import type { IDifference, INginxLogReadRecord } from '@/interfaces';
import { useMutation } from '@tanstack/react-query';
import { saveNginxLogSchedulerConfig } from '@/services/api';
import diff from 'microdiff';
import { isNum } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';
import { useRouter } from 'next/navigation';

export default function SaveNginxSchedulerConfigPage({
  source,
  find,
  translatedFields,
}: {
  source: INginxLogReadRecord[];
  find: INginxLogReadRecord | undefined;
  translatedFields: PrefixedTTranslatedFields<'logAdminPage'>;
}) {
  const isUpdate = !!find;
  const initForm = {
    logType: isUpdate ? find!.logType : 'ACCESS',
    logFilePath: isUpdate ? find!.logFilePath : '',
    fixedDelaySeconds: isUpdate ? find!.fixedDelaySeconds : 3,
    autostart: isUpdate ? find!.autostart : false,
  };
  const { show } = useToast();
  const [form, setForm] = useState<Partial<INginxLogReadRecord>>(initForm);
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);
  const router = useRouter();

  const saveNginxLogSchedulerConfigMutation = useMutation(
    saveNginxLogSchedulerConfig,
  );

  useEffect(() => {
    const diffData = diff(initForm, form);
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();

      let _form = form as any;
      const _find = source.find((item) => item.logType === form.logType);
      if (_find) {
        _form = { ..._find, ...form };
      }

      await saveNginxLogSchedulerConfigMutation.mutateAsync({
        data: _form,
      });

      show({
        type: 'SUCCESS',
        message: isUpdate
          ? translatedFields.updateCompleted
          : translatedFields.saveCompleted,
      });

      setTimeout(() => {
        show({
          type: 'PRIMARY',
          message: translatedFields.returning,
        });
      }, 1000);

      setTimeout(() => {
        router.back();
      }, 1500);
    } catch (e) {
      saveNginxLogSchedulerConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function checkForm() {
    const { logFilePath } = form;

    if (!logFilePath) {
      throw translatedFields.logFilePathRequired;
    }
  }

  function onChangeForm(
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'autostart') {
      setForm({
        ...form,
        autostart: value === 'true',
      });
    } else if (name === 'fixedDelaySeconds') {
      setForm({
        ...form,
        fixedDelaySeconds: isNum(value)
          ? parseInt(value)
          : initForm.fixedDelaySeconds,
      });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">{translatedFields.logType}</label>
          <select
            name="logType"
            value={form.logType}
            onChange={onChangeForm}
            className="form-select"
            aria-label="logType"
          >
            {['ACCESS', 'ERROR'].map((item) => {
              return (
                <option key={item} value={item}>
                  {(translatedFields as any).enums.logType[item]}
                </option>
              );
            })}
          </select>
        </div>

        <div>
          <label className="form-label">{translatedFields.logFilePath}</label>
          <input
            className="form-control"
            name="logFilePath"
            value={form.logFilePath}
            onChange={onChangeForm}
            aria-describedby="logFilePath"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.fixedDelaySeconds}
          </label>
          <input
            type="number"
            min={1}
            className="form-control"
            name="fixedDelaySeconds"
            value={form.fixedDelaySeconds}
            onChange={onChangeForm}
            aria-describedby="fixedDelaySeconds"
          />
        </div>

        <div>
          <label className="form-label">{translatedFields.autostart}</label>
          <select
            name="autostart"
            value={form.autostart + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="autostart"
          >
            {['true', 'false'].map((item) => {
              return (
                <option key={item} value={item}>
                  {item}
                </option>
              );
            })}
          </select>
        </div>

        <button
          type="submit"
          disabled={
            saveNginxLogSchedulerConfigMutation.isLoading || isDisabledSave
          }
          className="btn btn-success col col-lg-2 my-4"
        >
          {saveNginxLogSchedulerConfigMutation.isLoading && (
            <Spinner classs="me-2" />
          )}
          {isUpdate ? translatedFields.update : translatedFields.save}
        </button>
      </form>
    </Box>
  );
}
